//
//  NDMineView.swift
//  NyamanDana
//
//  Created by 李永彬 on 2025/10/8.
//

import SwiftUI

struct NDMineView: View {
    
    @Environment(\.presentationMode) var presentationMode
    @Environment(\.navigationManager) var navManager
    @State var phoneNumber: String = ""
    
    private let toolModels: [NDMineToolModel] = [
        NDMineToolModel(title: localizedString("My order"),
                        normalIcon: "mine_order_icon"),
        NDMineToolModel(title: localizedString("Customer Service"),
                        normalIcon: "mine_customer_icon"),
        NDMineToolModel(title: localizedString("Privacy Policy"),
                        normalIcon: "mine_pra_icon")
    ]
    
    var body: some View {
        let baseConfig = NDBaseConfig(
            backgroundColor: .clear,
            showNavigationBar: true,
            hiddenTabbar: false
        )
        let navigationConfig = NavigationConfig(
            title: localizedString("Personal Center"),
            showSystemBackButton: false
        )
        
        NDBaseContentView(
            baseConfig: baseConfig,
            navigationConfig: navigationConfig
        ) {
            
            VStack(spacing: 5) {
                HStack {
                    Image("mine_touoxiang")
                        .scaledToFit()
                        .frame(width: 70, height: 70)
                    Text(phoneNumber)
                        .font(.system(size: 20))
                        .foregroundColor(Color(hex: "#271F24"))
                        .padding(.leading, 10)
                    Spacer()
                    
                    Button(action: settingAction) {
                        Image("mine_setting_icon")
                            .scaledToFit()
                            .frame(width: 15, height: 15)
                    }
                    .frame(width: 40, height: 40)
                }
                .padding(.top, 10)
                .padding(.leading, 32)
                .padding(.trailing, 25)
                
                toolItemContentView
                
                Image(WJAppEnvironment.shared.currentCountry == .india ? "mine_banner" : "mine_banner_id")
                    .resizable()
                    .scaledToFit()
                    .frame(maxWidth: .infinity)
                    .padding(.horizontal, 16)
                    .padding(.top, 10)

                Spacer()
            }
        }
        .onAppear(perform: {
            NDProgressHUD.show()
            self.phoneNumber = (NDUserDefaults.shared.retrieveText(for: NDPhoneNumberKey) ?? "").maskMiddleCharacters()
            DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
                NDProgressHUD.dismiss()
            }
        })
        .onReceive(NotificationCenter.default.publisher(for: .schemeRefreshMine)) { _ in
            NDProgressHUD.show()
            self.phoneNumber = (NDUserDefaults.shared.retrieveText(for: NDPhoneNumberKey) ?? "").maskMiddleCharacters()
            DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
                NDProgressHUD.dismiss()
            }
        }
    }
    
    var toolItemContentView: some View {
        HStack(spacing: 0) {
            ForEach(0..<toolModels.count, id: \.self) { index in
                NDMineToolItem(model: toolModels[index])
                    .frame(maxWidth: .infinity)
                    .frame(height: 122)
                    .onTapGesture {
                        clickToolItem(index)
                    }
            }
        }
        .background(
            Color(hex: "#FFFFFF")
                .cornerRadius(12)
        )
        .padding(.horizontal, 16)
    }
    
    func settingAction() {
        navManager.wrappedValue.pushView(tag: mainNav) {
            NDLogoutView()
        }
    }
    
    func clickToolItem(_ index: Int) {
        switch index {
        case 0:
            switchToTab(index: 1)
        case 1: // 客服中心
            let url = NDAPIDomain.h5.rawValue + "citel"
//            let url = "http://149.129.255.14:10703/test?"
            goToWebView(url)
        case 2: // 隐私协议
            let url = NDAPIDomain.h5.rawValue + "potamoie"
            goToWebView(url)
        default:
            break
        }
    }
    
    func switchToTab(index: Int) {
        NotificationCenter.default.post(
            name: .switchTab,
            object: nil,
            userInfo: [TabSwitchKeys.tabIndex: 1]
        )
    }
    
    func goToWebView(_ urlString: String) {
        let webUrlStr = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
        print("webUrlStr: \(webUrlStr ?? "")")
        navManager.wrappedValue.pushView(tag: mainNav) {
            NDWebView(urlString: webUrlStr,
                      isFollowOrder: false,
                      isPresent: false)
        }
    }
}


struct NDMineToolItem: View {
    let model: NDMineToolModel
    var body: some View {
        VStack(alignment: .center) {
            Image(model.normalIcon)
            Text(model.title)
                .multilineTextAlignment(.center)
                .font(.system(size: 14))
                .foregroundColor(Color(hex: "#271F24"))
        }
        .frame(maxWidth: .infinity,
               maxHeight: .infinity,
               alignment: .center)
        .background(Color.clear)
    }
}

struct NDMineToolModel {
    let title: String
    let normalIcon: String
}

